package com.aaron.aaronnews;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.aaron.custom.CustomSimpleAdapter;
import com.aaron.model.Category;
import com.aaron.service.SyncHttp;
import com.aaron.util.DensityUtil;
import com.aaron.util.StringUtil;
import com.aaron.util.UrlUtil;

public class MainActivity extends Activity {
	
	private final int COLUMNWIDTHPX = 105;
	private final int FLINGVELOCITYPX = 800; //滚动距离
	
	private final int NEWSCOUNT = 5;
	
	private int mColumnWidthDip;
	private int mFlingVelocityDip;
	
	private ArrayList<HashMap<String, Object>> newsList;
	//刷新按钮
	private Button refreshButton;
	
	public int cid; //新闻分类id
	public String categoryTitleName; //新闻分类名称
	
	private ListView newListView;
	private View footer;
	private boolean finish = true;// 是否加载完成
	
	private SimpleAdapter newlistAdapter;
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		try{
			//获取新闻分类
			String[] categoryArray = getResources().getStringArray(R.array.categories);
			//把新闻分类保存到List中
			final List<HashMap<String, Category>> categories = new ArrayList<HashMap<String, Category>>();
			for(int i=0;i<categoryArray.length;i++){
				String[] temp = categoryArray[i].split("[|]");
				if(temp.length == 2){
					int cid = StringUtil.string2Int(temp[0]);
					String title = temp[1];
					Category category = new Category(cid, title);
					HashMap<String, Category> map = new HashMap<String,Category>();
					map.put("category_title", category);
					categories.add(map);
				}
			}
			CustomSimpleAdapter categoryAdapter = new CustomSimpleAdapter(this, categories, 
					R.layout.category_title, new String[]{"category_title"}, new int[]{R.id.category_title});
			
			
			cid = 1;
			categoryTitleName = categories.get(0).get("category_title").getTitle();
			
			mColumnWidthDip = DensityUtil.px2dip(this, COLUMNWIDTHPX);
			mFlingVelocityDip = DensityUtil.px2dip(this, FLINGVELOCITYPX);
			GridView category = new GridView(this);
			category.setColumnWidth(mColumnWidthDip);
			category.setNumColumns(GridView.AUTO_FIT);
			category.setGravity(Gravity.CENTER); //设置对齐方式
			//设置单元格选择是背景色为透明，这样选择时就不现实黄色背景
			category.setSelector(new ColorDrawable(Color.TRANSPARENT));
			int width = mColumnWidthDip * categories.size();
			LayoutParams params = new LayoutParams(width, LayoutParams.WRAP_CONTENT);
			category.setLayoutParams(params);
			category.setAdapter(categoryAdapter);
			
			LinearLayout lineaLayout = (LinearLayout)findViewById(R.id.category_layout);
			lineaLayout.addView(category);
			newListView = (ListView)findViewById(R.id.news_list);
			
			category.setOnItemClickListener(new OnItemClickListener() {
	
				@SuppressLint("ResourceAsColor")
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					TextView categoryTitle;
					//恢复每个单元格背景色
					for(int i=0;i<parent.getCount();i++){
						categoryTitle = (TextView) parent.getChildAt(i);
						categoryTitle.setTextColor(0xFFADB2AD);
						categoryTitle.setBackgroundDrawable(null);
					}
					//设置选择的单元格的背景色
					categoryTitle = (TextView)view;
					categoryTitle.setTextColor(0xFFFFFFFF);
					categoryTitle.setBackgroundResource(R.drawable.categorybar_item_background);
					
					cid = categories.get(position).get("category_title").getCid();
					categoryTitleName = categories.get(position).get("category_title").getTitle();
					String urlParams = "startnid=0&count=" + NEWSCOUNT + "&cid=" + cid;
					//ListView newListView = (ListView)findViewById(R.id.news_list);
					
					PageTask task = new PageTask(newListView, MainActivity.this,newsList);
					task.execute(UrlUtil.HOST + UrlUtil.CATAGORYNEWS, urlParams, "0");
				}
			});
			
			final HorizontalScrollView categorybarScrollview = (HorizontalScrollView)findViewById(R.id.categorybar_scrollview);
			Button categoryRightButton = (Button)findViewById(R.id.category_but_right);
			categoryRightButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					categorybarScrollview.fling(mFlingVelocityDip);
				}
			});
			
			newsList = new ArrayList<HashMap<String,Object>>();
			
			refreshButton = (Button)findViewById(R.id.titlebar_refresh);
			refreshButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					String urlParams = "startnid=0&count=" + NEWSCOUNT + "&cid=" + cid;
					ListView newListView = (ListView)findViewById(R.id.news_list);
					
					PageTask task = new PageTask(newListView, MainActivity.this,newsList);
					task.execute(UrlUtil.HOST + UrlUtil.CATAGORYNEWS, urlParams, "0");
				}
			});
			
			String urlParams = "startnid=0&count=" + NEWSCOUNT + "&cid=" + cid;
			PageTask task = new PageTask(newListView, this, newsList);
			task.execute(UrlUtil.HOST + UrlUtil.CATAGORYNEWS, urlParams, "0");
			
			footer = View.inflate(MainActivity.this, R.layout.footer, null);
			newlistAdapter = new SimpleAdapter(this, newsList, R.layout.newslist_item, 
					new String[]{"newslist_item_title","newslist_item_digest", "newslist_item_from", "newslist_item_ptime"}, 
					new int[]{R.id.news_list_title, R.id.news_list_zhaiyao, R.id.news_list_from, R.id.news_list_time});
			
			// 在增加listview的页脚之前，需要提前设置一次
			newListView.addFooterView(footer);
			newListView.setAdapter(newlistAdapter);
			// 然后再次将页脚删除掉
			newListView.removeFooterView(footer);
			
			
			
			
			// 滚动监听事件
			newListView.setOnScrollListener(new MyOnScrollListener());
			newListView.setOnItemClickListener(new OnItemClickListener() {
	
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
					intent.putExtra("categoryTitle", categoryTitleName);
					intent.putExtra("newsData", newsList);
					intent.putExtra("position", position);
					startActivity(intent);
				}
			});
			
		}catch(Exception e){
			Log.e("oncreate", e.getMessage());
		}
	}
	
	private final class MyOnScrollListener implements OnScrollListener {
		
		// 滚动状态发生改变时
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			Log.i("i", " scrollState " + scrollState);
		}

		// 当list开始滚动时
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// 最下面的条目数
			final int totalCount = firstVisibleItem + visibleItemCount;
			// 当翻到最后一条数据时
			if (totalCount > 0 && totalCount == totalItemCount && finish) {
				finish = false;
				// 添加页脚
				newListView.addFooterView(footer);
				String urlParams = "startnid=" + newsList.size() + "&count=" + NEWSCOUNT + "&cid=" + cid;
				PageTask task = new PageTask(newListView, MainActivity.this, newsList);
				task.execute(UrlUtil.HOST + UrlUtil.CATAGORYNEWS, urlParams, "1");
			}
		}
	}
	
	class PageTask extends AsyncTask<String, Integer, String>{

		private ListView newListView;
		private MainActivity mainActivity;
		private List<HashMap<String, Object>> newsList;
		
		public PageTask(ListView listView, MainActivity activity, List<HashMap<String, Object>> list){
			super();
			this.newListView = listView;
			this.mainActivity = activity;
			this.newsList = list;
		}
		
		@Override
		protected String doInBackground(String... params) {
			String res = "";
			if(params.length==3){
				String urlStr = params[0];
				String urlParams = params[1];
				String firstTime = params[2];
				if("0".equals(firstTime)){
					newsList.clear();
				}
				SyncHttp http = new SyncHttp();
				try {
					Log.w("http", "获取网络");
					String returnJson = http.httpGet(urlStr, urlParams);
					JSONObject jsonObj = new JSONObject(returnJson);
					int retCode = jsonObj.getInt("ret");
					if(0 == retCode){
						JSONObject dataObject = jsonObj.getJSONObject("data");
						//获取返回数目
						int totalNum = dataObject.getInt("totalnum");
						if(totalNum > 0){
							//获取返回新闻集合
							JSONArray newsArray = dataObject.getJSONArray("newslist");
							for(int i=0; i< newsArray.length(); i++){
								JSONObject newsObject = (JSONObject)newsArray.opt(i);
								HashMap<String, Object> hashMap = new HashMap<String, Object>();
								hashMap.put("nid", newsObject.getInt("nid"));
								hashMap.put("newslist_item_title", newsObject.getString("title"));
								hashMap.put("newslist_item_digest", newsObject.getString("digest"));
								hashMap.put("newslist_item_from", newsObject.getString("source"));
								hashMap.put("newslist_item_ptime", newsObject.getString("ptime"));
								hashMap.put("newslist_item_comments", newsObject.getString("commentcount"));
								newsList.add(hashMap);
							}
						}else{
							res = "该栏目下暂时没有新闻！";
						}
					}else {
						res = "获取新闻失败！";
					}
				} catch (Exception e) {
					Log.e("doInBackground", e.getMessage());
					res = "获取新闻失败！";
				}
			}
			return res;
		}
	

		@Override  
		protected void onPostExecute(String result) {  
			try{
				newlistAdapter.notifyDataSetChanged();
				
				// 将页脚删除掉
				if (newListView.getFooterViewsCount() > 0) {
					newListView.removeFooterView(footer);
				}
				
				if(!"".equals(result)){
					Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
				}else{
					finish = true;
				}
			}catch(Exception e){
				Log.e("onPostExecute", e.getMessage());
			}
		}  


	}
}
